package src.数据结构.顺序表;

public class SequenceList<OBJ> {
    private OBJ[] list;
    private int length;

    public SequenceList() {
        this.list = (OBJ[]) new Object[16];
        this.length = 0;
    }

    // 初始化表
    public SequenceList(int capt) {
        this.list = (OBJ[]) new Object[capt];
        this.length = 0;
    }

    // 判断表是否为空
    public boolean isEmpty() {
        return this.length == 0;
    }

    // 获取表大小
    public void size() {
        System.out.println("元素个数："+this.length+" 表大小："+this.list.length);
    }

    // 返回指定索引的值
    public OBJ get(int index) {
        return this.list[index];
    }

    // 插入数据
    public void add(OBJ obj) {
        if(this.length == this.list.length){
            resize();
        }
        this.list[length++] = obj;
    }

    public void insert(int i, OBJ obj) {
        if(this.length == this.list.length){
            resize();
        }
        // 检查插入位置是否合法
        if (i < 0 || i > this.length) {
            System.out.println("插入位置不合法");
            return;
        }
        // 移动 i 及以后的元素一位
        for (int j = this.length - 1; j >= i; j--) {
            this.list[j + 1] = this.list[j];
        }
        // 给空缺值赋值
        this.list[i] = obj;
        // 表长度加1
        this.length += 1;
    }

    // 删除数据
    public OBJ pop(int index) {
        // 记录index的值
        OBJ data = this.list[index];
        // 索引i处及后面的元素前移动一位
        for (int i = index; i < this.length; i++) {
            this.list[i] = this.list[i + 1];
        }
        this.length -= 1;
        if(this.length<this.list.length/4){
            resize(this.list.length/2);
        }
        return data;
    }

    public OBJ pop() {
        // 记录index的值
        OBJ data = this.list[this.length-1];
        this.length -= 1;
        if(this.length<this.list.length/4){
            resize(this.list.length/2);
        }
        return data;
    }

    // 清空数据
    public void clear() {
        this.length = 0;
    }

    // 查询元素的索引
    public int indexOf(OBJ obj) {
        for (int i = 0; i < this.length; i++) {
            if (this.list[i].equals(obj)) {
                return i;
            }
        }
        return -1;
    }

    // 遍历表
    public void show() {
        for (int i = 0; i < this.length; i++) {
            System.out.print(this.list[i] + " ");
        }
    }

    // 扩容
    public void resize(){
        // 定义一个临时数组
        OBJ[] tmp = this.list;
        list = (OBJ[]) new Object[this.length*2];
        for (int i = 0; i < this.length; i++) {
            list[i] = tmp[i];
        }
    }

    public void resize(int newSize){
        // 定义一个临时数组
        OBJ[] tmp = this.list;
        list = (OBJ[]) new Object[newSize];
        for (int i = 0; i < this.length; i++) {
            list[i] = tmp[i];
        }
    }

}
